package com.bil.socket.proxy;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 
 * @author litong
 * 仅仅接受服务端响应的数据,响应到客户端
 */
@Slf4j
public class ReceiveThread extends Thread {

  private Socket remoteServerSocket;
  private Socket clientSocket;

  public ReceiveThread(Socket remoteServerSocket, Socket clientSocket) {
    this.remoteServerSocket = remoteServerSocket;
    this.clientSocket = clientSocket;
  }

  @Override
  public void run() {
    try {
      InputStream in = remoteServerSocket.getInputStream();
      OutputStream out = clientSocket.getOutputStream();
      byte[] buf = new byte[1024 * 1024];
      int len = 0;
      int increment = 1;
      while ((len = in.read(buf)) != -1) {
        out.write(buf, 0, len);
        out.flush();
        log.info("第{}次响应,数据长度{},响应数据\r\n{}", increment++, len, new String(buf, 0, len));
      }
      log.info("接收响应完成:{}", remoteServerSocket);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      log.info("finally");
      IOUtils.closeQuietly(clientSocket);
      IOUtils.closeQuietly(remoteServerSocket);
    }
  }
}